package handler

import (
	"day116/model"
	"github.com/gin-gonic/gin"
	"strconv"
)

func MerHouseAdd(c *gin.Context) {
	name := c.PostForm("name")
	merNo, _ := strconv.Atoi(c.PostForm("mer_no"))
	status := c.PostForm("status")
	data := model.MerHouse{
		Name:   name,
		MerNo:  merNo,
		Status: status,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func OrderAdd(c *gin.Context) {
	mid, _ := strconv.Atoi(c.PostForm("mid"))
	price, _ := strconv.Atoi(c.PostForm("price"))
	employee := c.PostForm("employee")
	data := model.Order{
		Mid:      mid,
		Price:    price,
		Employee: employee,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var data []model.MerHouseOrder
	model.DB.Table("orders").
		Select(
			"mer_houses.name as Name",
			"mer_houses.mer_no as MerNo",
			"mer_houses.status as Status",
			"orders.id as Oid",
			"orders.mid as Mid",
			"orders.price as Price",
			"orders.employee as Employee",
		).
		Joins("left join mer_houses on mer_houses.id = orders.mid").
		Offset(offset).
		Limit(size).
		Find(&data)
	var total int64
	model.DB.Table("orders").Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  data,
		"total": total,
	})
	return
}
func Detail(c *gin.Context) {
	oid, _ := strconv.Atoi(c.Query("oid"))
	var data model.MerHouseOrder
	model.DB.Table("orders").
		Select(
			"mer_houses.name as Name",
			"mer_houses.mer_no as MerNo",
			"mer_houses.status as Status",
			"orders.id as Oid",
			"orders.mid as Mid",
			"orders.price as Price",
			"orders.employee as Employee",
		).
		Joins("left join mer_houses on mer_houses.id = orders.mid").
		Where("orders.id = ?", oid).
		Limit(1).
		Find(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": data,
	})
	return
}
